package RedisManager

import (
	LogUtils "IMServices/LogService"
	"context"
	"errors"
	"fmt"

	"github.com/go-redis/redis/v8"
)

type RedisClient struct {
	ctx        context.Context
	rdb        *redis.Client
	redisAddr  string
	poolSize   int
	password   string
	dbIndex    int
	maxRetries int
}

// RedisPipelineSet 批量设置键值对
func (r *RedisClient) RedisPipelineSet(listCommon map[string]string) {
	pipe := r.rdb.Pipeline()
	for k, v := range listCommon {
		pipe.Set(r.ctx, k, v, 0)
	}
	_, err := pipe.Exec(context.Background())
	if err != nil {
		panic(err)
	}
}

// RedisPipelineGet 批量获取值
func (r *RedisClient) RedisPipelineGet(listCommon []string) []string {

	var result []string
	// 创建 Redis 批处理器
	pipe := r.rdb.Pipeline()

	// 批量获取 key 对应的 value
	var cmds []*redis.StringCmd
	for _, key := range listCommon {
		cmd := pipe.Get(context.Background(), key)
		cmds = append(cmds, cmd)
	}
	_, err := pipe.Exec(context.Background())
	if err != nil {
		panic(err)
	}
	// 处理获取到的结果
	for i, cmd := range cmds {
		result = append(result, cmd.Val())
		fmt.Printf("key=%s, value=%s\n", listCommon[i], cmd.Val())
	}

	return result
}

// GetRedisList 获取redis中的列表
func (r *RedisClient) GetRedisList(listName string) (result []string) {
	// 获取列表
	listValues, err := r.rdb.LRange(r.ctx, listName, 0, -1).Result()
	if err != nil {
		fmt.Println(err)
	}
	return listValues
}

// GetRedisValue 获取一个键的值
func (r *RedisClient) GetRedisValue(redisKey string) string {
	val, err := r.rdb.Get(r.ctx, redisKey).Result()
	if err == redis.Nil {
		fmt.Println(redisKey + " does not exist")
	} else if err != nil {
		panic(err)
	} else {
		fmt.Println(redisKey+":", val)
	}
	fmt.Println(redisKey+":", val)
	return val
}

// SetRedisValue 存储一个键值对
func (r *RedisClient) SetRedisValue(redisKey string, redisValue string) error {
	err := r.rdb.Set(r.ctx, redisKey, redisValue, 0).Err()
	if err != nil {
		return err
	}
	return nil
}

func (r *RedisClient) DelRedisKey(redisKey string) error {
	// 删除一个键
	err := r.rdb.Del(r.ctx, redisKey).Err()
	if err != nil {
		panic(err)
	}
	return err
}

func (r *RedisClient) StartRedisService(addr string, password string, dbIndex int, maxRetries int, poolSize int) error {
	r.redisAddr = addr
	r.password = password
	r.dbIndex = dbIndex
	r.maxRetries = maxRetries
	r.poolSize = poolSize
	r.ctx = context.Background()
	// 创建一个 Redis 客户端
	r.rdb = redis.NewClient(&redis.Options{
		Addr:       addr,
		Password:   password,   // no password set
		DB:         dbIndex,    // use default DB
		MaxRetries: maxRetries, //最大重连次数
		PoolSize:   poolSize,   //线程池大小
	})

	if r.rdb == nil {
		LogUtils.LogError("redis数据库连接失败 : ", addr)
		return errors.New("redis连接失败")
	}
	return nil
}
